package com.example.zwx.myapplication;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.example.zwx.myapplication.Callback.OnBleSendListener;
import com.example.zwx.myapplication.Callback.OnBleStatusChangedListener;
import com.example.zwx.myapplication.utils.L;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/2/23.
 */
public class SimpleRemoteActivity extends Activity implements View.OnClickListener {
    private TextView sendText, consleText;
    private Button btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0, btnClearText, btnClearConsle, btnSend;
    private ToggleButton mSwitch, parseModeSwitch;
    private StringBuffer dataBuffer, consleBuffer;
    private ScrollView mScrollView;

    private BleManager mBleManager;
    private boolean isSingleKeyMode = true;
    public static boolean parseModeSelf = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple_remote);
        sendText = (TextView) findViewById(R.id.text_data);
        consleText = (TextView) findViewById(R.id.consle_result);
        mSwitch = (ToggleButton) findViewById(R.id.switch_mode);
        parseModeSwitch = (ToggleButton) findViewById(R.id.switch_parse_mode);
        btn0 = (Button) findViewById(R.id.btn0);
        btn1 = (Button) findViewById(R.id.btn1);
        btn2 = (Button) findViewById(R.id.btn2);
        btn3 = (Button) findViewById(R.id.btn3);
        btn4 = (Button) findViewById(R.id.btn4);
        btn5 = (Button) findViewById(R.id.btn5);
        btn6 = (Button) findViewById(R.id.btn6);
        btn7 = (Button) findViewById(R.id.btn7);
        btn8 = (Button) findViewById(R.id.btn8);
        btn9 = (Button) findViewById(R.id.btn9);
        btnClearText = (Button) findViewById(R.id.btn_clear);
        btnSend = (Button) findViewById(R.id.btn_send);
        btnClearConsle = (Button) findViewById(R.id.clear_consle);
        mScrollView = (ScrollView) findViewById(R.id.scroll_view);

        btn0.setOnClickListener(this);
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
        btn3.setOnClickListener(this);
        btn4.setOnClickListener(this);
        btn5.setOnClickListener(this);
        btn6.setOnClickListener(this);
        btn7.setOnClickListener(this);
        btn8.setOnClickListener(this);
        btn9.setOnClickListener(this);
        btnClearText.setOnClickListener(this);
        btnSend.setOnClickListener(this);
        btnClearConsle.setOnClickListener(this);

        dataBuffer = new StringBuffer();
        consleBuffer = new StringBuffer();
        mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isSingleKeyMode = !isChecked;
                dataBuffer = null;
                dataBuffer = new StringBuffer();
                sendText.setText(dataBuffer.toString());
            }
        });

        parseModeSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                parseModeSelf = !isChecked;
                dataBuffer = new StringBuffer();
                sendText.setText(dataBuffer.toString());
            }
        });

        mBleManager = BleManager.getInstance(this);
        final ProgressDialog dialog = new ProgressDialog(this);
        dialog.setCancelable(false);
        dialog.setTitle("正在连接BLE设备，请稍后...");
        dialog.show();
        mBleManager.init(new OnBleStatusChangedListener() {
            @Override
            public void onInitSuccess() {
                L.d("蓝牙服务初始化成功");
            }

            @Override
            public void onInitFailed(int resultCode, String resultMessage) {
                AppMsg.showToast(SimpleRemoteActivity.this, "蓝牙服务初始化失败");
                dialog.dismiss();
            }

            @Override
            public void onBleServiceBinded() {
                L.d("后台蓝牙服务绑定成功");
            }

            @Override
            public void onBleServiceUnBinded() {
                L.d("蓝牙服务已解绑");
            }

            @Override
            public void onDeviceConnected() {
                AppMsg.showToast(SimpleRemoteActivity.this, "已连接到ble设备");
                dialog.dismiss();
            }

            @Override
            public void onDeviceDisconnected() {
                AppMsg.showToast(SimpleRemoteActivity.this, "蓝牙设备已断开！");
                dialog.dismiss();
            }
        }, true);

        mBleManager.registOnBleSendFeedbackListener(new OnBleSendListener() {
            @Override
            public void onResult(BleIRData data) {
                appendConsle(data.toString());
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn0:
                if (!isSingleKeyMode) {
                    if (dataBuffer.length() != 0 && dataBuffer.length() < 3) {
                        dataBuffer.append("0");
                        sendText.setText(dataBuffer.toString());
                    }
                }
                break;
            case R.id.btn1:
                if (!isSingleKeyMode) {
                    appendGroupKey("1");
                } else {
                    sendSingleKey("1");
                }
                break;
            case R.id.btn2:
                if (!isSingleKeyMode) {
                    appendGroupKey("2");
                } else {
                    sendSingleKey("2");
                }
                break;
            case R.id.btn3:
                if (!isSingleKeyMode) {
                    appendGroupKey("3");
                } else {
                    sendSingleKey("3");
                }
                break;
            case R.id.btn4:
                if (!isSingleKeyMode) {
                    appendGroupKey("4");
                } else {
                    sendSingleKey("4");
                }
                break;
            case R.id.btn5:
                if (!isSingleKeyMode) {
                    appendGroupKey("5");
                } else {
                    sendSingleKey("5");
                }
                break;
            case R.id.btn6:
                if (!isSingleKeyMode) {
                    appendGroupKey("6");
                } else {
                    sendSingleKey("6");
                }
                break;
            case R.id.btn7:
                if (!isSingleKeyMode) {
                    appendGroupKey("7");
                } else {
                    sendSingleKey("7");
                }
                break;
            case R.id.btn8:
                if (!isSingleKeyMode) {
                    appendGroupKey("8");
                } else {
                    sendSingleKey("8");
                }
                break;
            case R.id.btn9:
                if (!isSingleKeyMode) {
                    appendGroupKey("9");
                } else {
                    sendSingleKey("9");
                }
                break;
            case R.id.btn_clear:
                dataBuffer = null;
                dataBuffer = new StringBuffer();
                sendText.setText(dataBuffer.toString());
                break;
            case R.id.btn_send:
                List<String> keys = getIRKeys(dataBuffer.toString());
                dataBuffer = null;
                dataBuffer = new StringBuffer();
                sendText.setText(dataBuffer.toString());
                if (keys != null) {
                    send(keys);
                }

                break;
            case R.id.clear_consle:
                consleBuffer = null;
                consleBuffer = new StringBuffer();
                consleText.setText(consleBuffer.toString());
                break;
        }
    }

    private void appendGroupKey(String s) {
        if (dataBuffer == null) {
            dataBuffer = new StringBuffer();
        }
        if (dataBuffer.length() < 3) {
            dataBuffer.append(s);
        }
        sendText.setText(dataBuffer.toString());
    }

    private void appendConsle(String text) {
        if (consleBuffer == null) {
            consleBuffer = new StringBuffer();
        }

        consleBuffer.append("\n");
        consleBuffer.append(text);
        consleBuffer.append("\n");

        consleText.setText(consleBuffer.toString());
        scrollToBottom();
    }

    private void sendSingleKey(String s) {
        send(getIRKeys(s));
    }

    private void send(List<String> iRKeys) {
        mBleManager.sendIr(iRKeys);
    }

    private List<String> getIRKeys(String num) {
        if (num.isEmpty()) {
            return null;
        }
        List<String> keysList = new ArrayList<String>();
        int channelNum = Integer.parseInt(num);
        int h = channelNum / 100;
        int t = (channelNum - (h * 100)) / 10;
        int n = channelNum % 10;


        if (h != 0) {
            keysList.add(StbRemoteIR.irMap.get(h + ""));
            keysList.add(StbRemoteIR.irMap.get(t + ""));
            keysList.add(StbRemoteIR.irMap.get(n + ""));
            return keysList;
        } else if (t != 0) {
            keysList.add(StbRemoteIR.irMap.get(t + ""));
            keysList.add(StbRemoteIR.irMap.get(n + ""));
            return keysList;
        } else if (n != 0) {
            keysList.add(StbRemoteIR.irMap.get(n + ""));
            return keysList;
        }
        return null;
    }

    private void scrollToBottom() {
        mScrollView.post(new Runnable() {
            public void run() {
                mScrollView.smoothScrollTo(0, consleText.getBottom());
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BleManager.getInstance(this).destory();
    }
}